package com.lemon.exam.entity.po;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
import org.springframework.util.StringUtils;

import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Map;

/**
 * 试卷-答案表 持久层对象
 *
 * @author Lemon
 * @since 2025/05/17 10:51:17
 */
@Getter
@Setter
@ToString
@Table(value = "biz_paper_answer")
@Schema(name = "试卷-答案表")
@Accessors(chain = true)
public class PaperAnswerPO implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    @Id
    @Schema(description = "试题主键ID")
    @Column(value = "id")
    private Long id;

    @Schema(description = "试卷ID")
    @Column(value = "paper_id")
    private Long paperId;

    @Schema(description = "用户ID")
    @Column(value = "user_id")
    private Long userId;

    @Schema(description = "答案JSON对象 key:Excel的行号 value:答案")
    @Column(value = "answer")
    private String answer;

    @Schema(description = "交卷时间")
    @Column(value = "submit_time")
    private LocalDateTime submitTime;

    @Schema(description = "每道题的得分JSON对象 key:Excel的行号 value:得分")
    @Column(value = "question_score")
    private String questionScore;

    @Schema(description = "总得分")
    @Column(value = "total_score")
    private Double totalScore;

    @Schema(description = "是否及格 1是 0否")
    @Column(value = "passed")
    private Integer passed;

    @Transient
    @Schema(description = "用户姓名")
    private String userName;

    /**
     * 获取答案的Map对象
     *
     * @return Map<Integer, String []>
     */
    public Map<Integer, String[]> getAnswerMap() {
        return toMap(this.answer, new TypeReference<Map<Integer, String[]>>() {});
    }

    /**
     * 获取每道题的得分的Map对象
     *
     * @return Map<Integer, Double>
     */
    public Map<Integer, Double> getQuestionScoreMap() {
        return toMap(this.questionScore, new TypeReference<Map<Integer, Double>>() {});
    }

    /**
     * 转换为Map对象
     *
     * @param json
     * @param typeReference
     * @param <V>
     * @return
     */
    private <V> Map<Integer, V> toMap(String json, TypeReference<Map<Integer, V>> typeReference) {
        if (!StringUtils.hasText(json)) {
            return Collections.emptyMap();
        }
        try {
            return JSON.parseObject(json, typeReference);
        } catch (Exception e) {
            return Collections.emptyMap();
        }
    }
}
